package typeConversion

import (
	"errors"
	"fmt"
	"time"
)

//字符串2006-01-02 15:04:05、毫秒/秒时间戳
func ToTime(p_i interface{}) (time.Time, error) {
	if p_i == nil {
		return time.Now(), errors.New("too.typeConversion ToInt err: Parameters not supported, Parameters is nil")
	}
	switch p_i.(type) {
	case string:
		return time.Parse("2006-01-02 15:04:05", p_i.(string))
	case int:
		return int64ToTime(int64(p_i.(int)))
	case int64:
		return int64ToTime(p_i.(int64))
	case float32:
		return int64ToTime(int64(p_i.(float32)))
	case float64:
		return int64ToTime(int64(p_i.(float64)))
	default:
		return time.Now(), errors.New("too.typeConversion ToTime err: Parameters not supported,The parameter type is " + fmt.Sprintf("%T", p_i))
	}
}

//时间戳转时间
func int64ToTime(tStamp int64) (time.Time, error) {
	if isMillisecondTimestamp(tStamp) {
		//毫秒时间戳
		return time.Unix(0, tStamp*int64(time.Millisecond)), nil
	} else {
		//秒时间戳
		return time.Unix(tStamp, 0), nil
	}
}

//判断时间戳是毫秒还是秒
func isMillisecondTimestamp(timestamp int64) bool {
	return timestamp > 1000000000000
}
